package com.huiquan.elasticsearch;

import com.huiquan.analysis.domain.AnalysisSearchParam;
import com.huiquan.analysis.domain.AnalysisSentence;
import com.huiquan.elasticsearch.service.ElasticsearchService;
import com.huiquan.zs.service.ZsSentenceService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by chenqiang
 * Date: 2018/5/28
 * Time: 下午3:35
 */
@Controller
public class ESTestController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private TransportClient client;

    /**
     * 测试client
     */
    @ResponseBody
    @RequestMapping(value = "searchById.do")
    public ResponseEntity searchById(@RequestParam("id") String id) {
        GetResponse result = this.client.prepareGet("article","testarticle",id).get();
        return new ResponseEntity(result.getSource(),HttpStatus.OK);
    }


    @ResponseBody
    @RequestMapping(value = "searchByVocabulary.do")
    public ResponseEntity searchByVocabulary(@RequestParam("vocabulary") String vocabulary,@RequestParam("property") String property) {
        BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery();
        SortBuilder sortBuilder = SortBuilders.fieldSort("gmt_modified")
                .order(SortOrder.DESC);
        booleanQuery.must(QueryBuilders.matchQuery("label_status",1));
        booleanQuery.must(QueryBuilders.matchQuery("vocabulary",vocabulary));
        booleanQuery.mustNot(QueryBuilders.matchQuery("property",property));
        SearchRequestBuilder builder = this.client.prepareSearch("zsvocabandsentence")
                .setTypes("zsvocabandsentence")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(booleanQuery)
                .addSort(sortBuilder)
                .setFrom(0)
                .setSize(10000);

        System.out.println(builder);

        SearchResponse response =builder.get();
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();

        for(SearchHit hit : response.getHits()){
            result.add(hit.getSource());
        }

        System.out.println("总数量："+response.getHits().getTotalHits());
        System.out.println("耗时："+response.getTookInMillis());
        return new ResponseEntity(result,HttpStatus.OK);
    }

    /**
     * 测试client
     */
    @ResponseBody
    @RequestMapping(value = "testDemo.do")
    public ResponseEntity testDemo() {
        List<AnalysisSearchParam> searchParams = new ArrayList<>(); // 多词语查询
        AnalysisSearchParam searchParam = new AnalysisSearchParam();
//        searchParam.setVocabulary("小指");
//        searchParam.setProperty("O");
//        searchParam.setPosition1("");
//        searchParam.setPosition2("");
//        searchParam.setOppositePropertyFlag("0");
//        searchParam.setOppositePosition1Flag("0");
//
//        AnalysisSearchParam searchParam1 = new AnalysisSearchParam();
//        searchParam1.setVocabulary("小指");
//        searchParam1.setProperty("");
//        searchParam1.setPosition1("M");
//        searchParam1.setPosition2("");
//        searchParam1.setOppositePropertyFlag("0");
//        searchParam1.setOppositePosition1Flag("0");

        searchParam.setVocabulary("");
        searchParam.setProperty("");
        searchParam.setPosition1("");
        searchParam.setPosition2("");
        searchParam.setOppositePropertyFlag("0");
        searchParam.setOppositePosition1Flag("0");


        searchParams.add(searchParam);
//        searchParams.add(searchParam1);
        List<AnalysisSentence> list  = elasticsearchService.getZSLabeledListFromES(searchParams);
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i).toString());
        }

        return new ResponseEntity(null,HttpStatus.OK);
    }

    public List<Map<String,Object>> getZSListFromES(AnalysisSearchParam searchParam,int labelStatus){
        BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery();
        SortBuilder sortBuilder = SortBuilders.fieldSort("gmt_modified")
                .order(SortOrder.DESC);
        booleanQuery.must(QueryBuilders.matchQuery("label_status",labelStatus));
        if (StringUtils.isNotEmpty(searchParam.getVocabulary())) {
            booleanQuery.must(QueryBuilders.matchQuery("vocabulary",searchParam.getVocabulary()));
        }
        if (StringUtils.isNotEmpty(searchParam.getProperty())) {
            if ("0".endsWith(searchParam.getOppositePropertyFlag())) {
                booleanQuery.must(QueryBuilders.matchQuery("property",searchParam.getProperty()));
            }else{
                booleanQuery.mustNot(QueryBuilders.matchQuery("property",searchParam.getProperty()));
            }
        }
        if (StringUtils.isNotEmpty(searchParam.getPosition1())) {
            if ("0".endsWith(searchParam.getOppositePosition1Flag())) {
                booleanQuery.must(QueryBuilders.matchQuery("position1",searchParam.getPosition1()));
            }else{
                booleanQuery.mustNot(QueryBuilders.matchQuery("position1",searchParam.getPosition1()));
            }
        }
        if (StringUtils.isNotEmpty(searchParam.getPosition2())) {
            booleanQuery.must(QueryBuilders.matchQuery("position2",searchParam.getPosition2()));
        }

        SearchRequestBuilder builder = this.client.prepareSearch("zsvocabandsentence")
                .setTypes("zsvocabandsentence")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(booleanQuery)
                .addSort(sortBuilder)
                .setFrom(0)
                .setSize(10000);

        System.out.println(builder);

        SearchResponse response =builder.get();
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();

        for(SearchHit hit : response.getHits()){
            result.add(hit.getSource());
        }
        System.out.println("总数量："+response.getHits().getTotalHits());
        System.out.println("耗时："+response.getTookInMillis());
        return result;
    }
}
